package com.health.fragment.jtys;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.health.R;
import com.health.db.FDbManager;
import com.health.fragment.NovaFragment;
import com.health.idcard.entity.MyIdCardBean;
import com.health.model.DZJMJKKSQCodeImageBean;
import com.health.model.DZJMJKKXQcodeBean;
import com.health.model.DZJMJKKXcrzBean;
import com.health.model.NationBean;
import com.health.model.PeopleType;
import com.health.streadcard.ServerData;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.BD_DD_INFO;
import com.health.tablebean.BTDevice;
import com.health.tablebean.HD_PERSONAL_JKTZ;
import com.health.tablebean.JTYS_BASEINFO;
import com.health.tools.AssetManagerUtils;
import com.health.tools.DeviceUtil;
import com.health.tools.GlobalConts;
import com.health.tools.GlobalContsJTYS;
import com.health.tools.IDCardVerifyTool;
import com.health.tools.SPUtil;
import com.health.view.spinner.NiceSpinner;
import com.health.viewscontrols.CaptureActivity;
import com.health.viewscontrols.MainActivity_Menu_JTYS;
import com.health.viewscontrols.MainActivity_Menu_Tj;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.medical.BleMainActivity;
import com.health.viewscontrols.qyinfo.QYInfo;
import com.health.viewscontrols.settings.SystemSettingJMDZDAActivity;
import com.health.webservices.JmdzjkkWebService;
import com.health.webservices.WebServiceConts;
import com.health.webservices.dzjmjkkxml.DzjmjkkDataTool;
import com.health.widget.CommomDialog;
import com.health.widget.EditTextWithDate;
import com.litesuits.http.data.TypeToken;
import com.nova.view.NovaTextDialog;
import com.novabluetooth.views.BluetoothDeviceBindActivity2;
import com.senter.readcard.openapi.CardSDK;
import com.unpos.idCard.IdCardBean;
import com.unpos.idCard.readIDCard;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 家庭医生 --建档
 *
 * @author nova
 */
public class JTYSJD extends NovaFragment implements OnClickListener {
    private boolean scanSuccess = false;
    private static final String TAG = "Main_tj_loginFragment";
    private static final String ISTAG = "1";
    private NiceSpinner minzuSpinner;
    private Button loginBtn;
    private Button cancelBtn;
    private Button tiJianBtn;
    private EditText idNoEt;
    private EditText nameEt;
    private EditTextWithDate birthdayEt;
    private EditText addressEt;
    private RadioGroup sexRadio;
    protected String sex;
    private RadioButton mailRadio;
    private RadioButton famailRadio;
    private ARCHIVE_BASEINFO userInfo = new ARCHIVE_BASEINFO();
    private View baseView;
    FDbManager fDbManager = NovaApplication.fdbmanger;
    private boolean flag_fromIdCard = false;
    public static int CAMERA_REQUEST_CODE = 1;
    private int age;
    EditText exam_login_zhuyuan_et;//住院号
    LinearLayout layout_zhuyuan;
    private EditText exam_phone;
    private LinearLayout linear_sfycf;
    private CheckBox check_isycf;
    private ImageView iv_photo;
    private ImageView iv_smjmdzjkk;
    private ProgressDialog mProgressDialog;
    private Button readCard;//肯麦思pad

    private SoundPool soundPool;
    private MediaPlayer mediaPlayer = null;
    /**
     * 是否是连续读取
     */
    private volatile boolean isSequentialRead = false;

    private ExecutorService activeService = Executors.newSingleThreadExecutor();
    private MediaPlayer media;
    private boolean readSuccess = false;
    private boolean isFont = false;
    private IdCardBean idCardDataBean;
    private List<NationBean> nationBeanList = new ArrayList<>();
    private Button bt_create;
    private List<ARCHIVE_BASEINFO> idCardList;
    private String dkType;

    // ST710读卡器设备
    private CardSDK cardSDK;
    private boolean isReadingST710;
    private String st710Mac;

    private MyBroadcastReceiver myBroadcastReceiver;

    public class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                MyIdCardBean myIdCardBean = (MyIdCardBean) intent.getSerializableExtra("idcard_data");

                if (myIdCardBean != null && !TextUtils.isEmpty(myIdCardBean.getIdCard())) {
                    idNoEt.setText(myIdCardBean.getIdCard());
                    nameEt.setText(myIdCardBean.getName());
                    addressEt.setText(myIdCardBean.getAddress());
                    Log.e(TAG, "onReceive: " + myIdCardBean.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public View findViews(LayoutInflater inflater) {
        baseView = inflater.inflate(R.layout.mainactivity_login_tj, null);
        findViews(baseView);
        setData();
        loginBtn.setVisibility(View.GONE);
        tiJianBtn.setText("健康检测");
        if (DeviceUtil.compareDeviceName()) {
            initCard();
            initData();
        }
        initCardST710();

        IntentFilter filter = new IntentFilter("com.idcard.data");
        myBroadcastReceiver = new MyBroadcastReceiver();
        getActivity().registerReceiver(myBroadcastReceiver, filter);
        return baseView;
    }

    // ST710读卡器
    private void initCardST710() {
        cardSDK = CardSDK.getInstance(CardSDK.Mode.BlueTooth);
        //每种不同的通信方式，需要单独设置
        cardSDK.setContext(NovaApplication.getInstance());
        cardSDK.setServerAddress(ServerData.getCurrentServerAddress(getActivity()));
        cardSDK.setServerPort(Integer.parseInt(ServerData.getCurrentServerPort(getActivity())));
    }

    // ST710读卡器
    private void readCardST710() {
        if (TextUtils.isEmpty(st710Mac)) {
            List<BTDevice> btDevices = NovaApplication.fdbmanger.findAllBTByWhere(BTDevice.class,
                    "name = 'ST710读卡器'");
            if (btDevices != null && btDevices.size() > 0) {
                st710Mac = btDevices.get(0).getMacAddress();
            }
        }

        if (TextUtils.isEmpty(st710Mac)) {
            ToastUtils.showShort("请绑定读卡器设备！");
            startActivity(new Intent(getActivity(), BluetoothDeviceBindActivity2.class));
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    isReadingST710 = true;
                    if (cardSDK.registerBTCard(st710Mac)) {
                        final CardSDK.IDCardResult result = cardSDK.readCard_Sync();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                parseIdCardDataST710(result);
                            }
                        });
                    }
                    SystemClock.sleep(300);
                } finally {
                    isReadingST710 = false;
                }
            }
        }).start();
    }

    private void parseIdCardDataST710(CardSDK.IDCardResult result) {
        if (result == null) {
            ToastUtils.showShort("无返回结果");
            return;
        }

        if (result.getError() != CardSDK.Error.success) {
            ToastUtils.showShort(result.getError().getMsg());
            return;
        }

        JSONObject JsonObj;
        InputStream input = null;
        byte[] avatar = new byte[20 * 1024];

        try {

            media = MediaPlayer.create(getActivity(), R.raw.read_card_success);
            media.start();

            JsonObj = new JSONObject(result.getResult());
            String type = JsonObj.getString("type");

//            type
//            卡片类型，type值：
//            I：外国人
//            J：港奥台
//            长度为空的字符串:二代证
            if (type.equals("I")) {
//                nameTextView.setText(JsonObj.getString("name"));
//                tv_enname.setText(JsonObj.getString("enname"));
//                Labelehtnic.setText("");
//                Lableaddress.setText("国籍");
//                folkTextView.setText("");
//                addrTextView.setText(JsonObj.getString("ethnicity"));
//                tv_numberofissue.setText("");
//                tv_passnumber.setText("");
            } else if (type.equals("")) {
//                if (nationBeanList.size() <= 0) {
//                    String json = AssetManagerUtils.getJson("nation.json", getActivity());
//                    nationBeanList = GsonUtils.fromJson(json, new TypeToken<List<NationBean>>() {
//                    }.getType());
//                }
//                for (NationBean nationBean : nationBeanList) {
//                    if (nationBean.getCode().equals(idCardDataBean.nation)) {
//                        minzuSpinner.setText(nationBean.getNation());
//                        break;
//                    }
//                }
                idNoEt.setText(JsonObj.getString("cardNo"));
                nameEt.setText(JsonObj.getString("name"));
                addressEt.setText(JsonObj.getString("address"));
            } else if (type.equals("J")) {
//                Labelehtnic.setText("民族");
//                Lableaddress.setText("住址");
//                nameTextView.setText(JsonObj.getString("name"));
//                folkTextView.setText(JsonObj.getString("ethnicity"));
//                addrTextView.setText(JsonObj.getString("address"));
//
//                tv_numberofissue.setText(JsonObj.getString("numberofissue"));
//                tv_passnumber.setText(JsonObj.getString("passnumber"));
            }

            JSONArray javatar = JsonObj.getJSONArray("avatar");
            int len = javatar.length();

            for (int j = 0; j < len; j++) {
                avatar[j] = (byte) javatar.getInt(j);
            }
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        try {
            Bitmap photobm = null;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 1;
            input = new ByteArrayInputStream(avatar);

            SoftReference softRef = new SoftReference(BitmapFactory.decodeStream(input, null, options));
            photobm = (Bitmap) softRef.get();
            iv_photo.setImageBitmap(photobm);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void initCard() {
        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
    }

    private void initData() {
        mediaPlayer = MediaPlayer.create(getActivity(), R.raw.ok);
    }

    private void refresh(boolean isSequentialRead) {
        if (!isSequentialRead) {
            return;
        }
    }

    @Override
    public void setupView(View view) {
    }

    @Override
    public void addListener() {
        readCard.setOnClickListener(this);
        iv_smjmdzjkk.setOnClickListener(this);
        loginBtn.setOnClickListener(this);
        tiJianBtn.setOnClickListener(this);
        cancelBtn.setOnClickListener(this);
        birthdayEt.setOnClickListener(this);
        sexRadio.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (mailRadio.getId() == checkedId || famailRadio.getId() == checkedId) {
                    int radioButtonId = group.getCheckedRadioButtonId();
                    if (checkedId == R.id.exam_mail) {
                        sex = "男";
                    } else if (checkedId == R.id.exam_famail) {
                        sex = "女";
                    }
                    if ("女".equals(sex)) {
                        iv_photo.setImageResource(R.drawable.head_youth_y);
                    } else {
                        iv_photo.setImageResource(R.drawable.head_youth_x);
                    }
                    Log.e("tag", sex + "");
                    setISycfVisible(sex);
                }
            }
        });

        idNoEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String idNo = idNoEt.getText().toString();
                String idCard18 = null;
                if (idNo.length() == 15) {
                    if (IDCardVerifyTool.Validate(idNo).equals("")) {
                        idCard18 = IDCardVerifyTool.from15to18(19, idNo);
                    }
                } else if (idNo.length() == 18) {
                    idCard18 = idNo;
                }
                if (idCard18 != null && idCard18.length() == 18) {
                    if (IDCardVerifyTool.Validate(idNo).equals("")) {
                        // 正确的身份证号
                        Log.w("ddddd", "eeeeeeeee" + idCard18);
                        idCardList = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class,
                                "IDCARD = '" + idCard18 + "'");
                        String year = idCard18.substring(6, 10);
                        String mouth = idCard18.substring(10, 12);
                        String day = idCard18.substring(12, 14);
                        String birthdayStr = year + "-" + mouth + "" + "-" + day;
                        birthdayEt.setText(birthdayStr);
                        try {
                            age = GlobalConts.getAge(GlobalConts.dateFormat.parse(birthdayStr));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        String sexStr = idCard18.substring(16, 17);
                        if (Integer.parseInt(sexStr) % 2 == 0) {
                            famailRadio.setChecked(true);
                        } else {
                            mailRadio.setChecked(true);
                        }
                        setISycfVisible(sex);
                        if (idCardList.size() > 0) {
                            // 身份证号已存在
                            ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("数据已存在，不需要建档");
                            cleanData();
                            if (idCardList != null && idCardList.size() > 0) {
                                userInfo = idCardList.get(0);
                            }
                            jumpNext2();
                            return;
                        } else {
                            if (!flag_fromIdCard) {
                                // 如果不是从身份证读卡器读取
                                addressEt.setText("");
                                nameEt.setText("");
                                userInfo = new ARCHIVE_BASEINFO();
                            }
                        }

                    } else {
                        new AlertDialog.Builder(getActivity()).setTitle("温馨提示").setMessage("您输入的身份证号码有误，请重新输入！")
                                .setPositiveButton("确定", null).show();
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        exam_phone.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String mobile = exam_phone.getText().toString();
                if (mobile.length() == 11) {
                    if (!GlobalConts.isPhoneNumberValid(mobile)) {
                        ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("请输入正确的手机号码");
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void setData() {
        List<BD_DD_INFO> minzuList = fDbManager.findAllByWhereInInfoDB(BD_DD_INFO.class, "PARENTID = 'DM01-01'"," cast(SORT as int) asc");
        List<String> minzu = new ArrayList<String>();
        if (minzuList != null) {
            for (BD_DD_INFO info : minzuList) {
                minzu.add(info.getDATAINFO());
            }
        }
        minzuSpinner.attachDataSource(minzu);
//        minzuSpinner.setText("汉族");
    }

    public void findViews(View view) {
        dkType = NovaApplication.dkType;

        readCard = baseView.findViewById(R.id.read_card);
        idNoEt = (EditText) baseView.findViewById(R.id.exam_login_idcard_et);
        nameEt = (EditText) baseView.findViewById(R.id.exam_name_et);
        sexRadio = (RadioGroup) baseView.findViewById(R.id.exam_sex);
        mailRadio = (RadioButton) baseView.findViewById(R.id.exam_mail);
        famailRadio = (RadioButton) baseView.findViewById(R.id.exam_famail);
        birthdayEt = (EditTextWithDate) baseView.findViewById(R.id.exam_birthday);

        bt_create = (Button) baseView.findViewById(R.id.bt_create);

        LinearLayout ll_back = (LinearLayout) baseView.findViewById(R.id.ll_back);
        ll_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        birthdayEt.setDatePickerEnabled(false);
        birthdayEt.setClickable(false);
        addressEt = (EditText) baseView.findViewById(R.id.exam_address);
        minzuSpinner = (NiceSpinner) baseView.findViewById(R.id.exam_minzu_spinner);
        loginBtn = (Button) baseView.findViewById(R.id.exam_login_btn);
        tiJianBtn = baseView.findViewById(R.id.exam_tijian_btn);
        cancelBtn = (Button) baseView.findViewById(R.id.exam_login_cancel);
        birthdayEt.setBefore(new Date());
        exam_login_zhuyuan_et = baseView.findViewById(R.id.exam_login_zhuyuan_et);
//		get_zhuyuan=baseView.findViewById(R.id.get_zhuyuan);
        layout_zhuyuan = baseView.findViewById(R.id.layout_zhuyuan);
        exam_phone = (EditText) view.findViewById(R.id.exam_phone);
        linear_sfycf = (LinearLayout) view.findViewById(R.id.linear_sfycf);
        check_isycf = (CheckBox) view.findViewById(R.id.check_isycf);
        iv_photo = (ImageView) view.findViewById(R.id.iv_photo);
        iv_smjmdzjkk = (ImageView) view.findViewById(R.id.iv_smjmdzjkk);
        TextView tvJg = (TextView) view.findViewById(R.id.tv_jg);
        SharedPreferences shareDatas = getActivity().getSharedPreferences(SPUtil.SP_NAME, Context.MODE_PRIVATE);
        String jg = shareDatas.getString(SPUtil.STR_JDDW, "");
        if (null != jg) {
            tvJg.setText(jg);
        }

        if (NovaApplication.isBoolean_dzjmjkk()) {
            // 设置可见
            iv_smjmdzjkk.setOnClickListener(this);
            iv_smjmdzjkk.setVisibility(View.VISIBLE);
        } else {
            iv_smjmdzjkk.setVisibility(View.GONE);
        }

        if (NovaApplication.isBoolean_zhuyuan()) {
            layout_zhuyuan.setVisibility(View.VISIBLE);
        } else {
            layout_zhuyuan.setVisibility(View.GONE);
        }
        if (dkType.equals("外置读卡")) {
            readCard.setVisibility(View.VISIBLE);
        }
        bt_create.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.exam_login_btn:
                loginData();
                break;
            case R.id.bt_create:
                loginData2();
                break;
            case R.id.exam_tijian_btn:
                loginData1();
                break;
            case R.id.exam_login_cancel:
                cleanData();
                break;
            case R.id.iv_smjmdzjkk:
                getQuanXian();
                break;
            case R.id.read_card:
//                isSequentialRead = false;
                if ("内置读卡".equals(NovaApplication.dkType)) {
                    startNewReadRunnable();
                } else {
                    readCardST710();
                }
                break;
            default:
                break;
        }
    }

    private void startNewReadRunnable() {
        byte[] data = readIDCard.getIDdata();
        if (data != null && !readSuccess) {
            idCardDataBean = readIDCard.getIdCardDataBean(data);
            if (null != idCardDataBean) {
                Log.e(TAG, "run: " + idCardDataBean.toString());
                Log.e(TAG, "姓名 ：" + idCardDataBean.name + " 证件号码：" + idCardDataBean.idCard);
                inputIdCard();
            } else {
                ToastUtils.showShort("请拿开身份证，重新放置");
            }
        }
    }

//    private void startNewReadRunnable() {
//        Log.e(TAG, "startNewReadRunnable: " + isFont + readSuccess);
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                while (true) {
//                    try {
//                        synchronized (JTYSJD.class) {
//                            if (!isFont) continue;
//                            byte[] data = readIDCard.getIDdata();
//                            if (data != null && !readSuccess) {
//                                idCardDataBean = readIDCard.getIdCardDataBean(data);
//                                Log.e(TAG, "run: " + idCardDataBean.toString());
//                                if (null != idCardDataBean) {
//                                    Log.e(TAG, "姓名 ：" + idCardDataBean.name + " 证件号码：" + idCardDataBean.idCard);
//                                    inputIdCard();
//                                } else {
//                                    ToastUtils.showShort("请拿开身份证，重新放置");
//                                }
//                            }
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
////				while (isRead) {
////					try {
////						synchronized (JTYSJD.class) {
////							if (!isFont) continue;
////							byte[] data = readIDCard.getIDdata();
////							if (data != null && !readSuccess) {
////								idCardDataBean = readIDCard.getIdCardDataBean(data);
////								if (null != idCardDataBean) {
////									Log.e(TAG, "姓名 ：" + idCardDataBean.name + "      证件号码：" + idCardDataBean.idCard);
////									inputIdCard();
////								} else {
////									ToastUtils.showShort("请拿开身份证，重新放置");
////								}
////							}
////						}
////					} catch (Exception e) {
////						e.printStackTrace();
////					}
////				}
//            }
//        }).start();
//    }

    private void inputIdCard() {
        try {
            Log.d(TAG, "获取图片");
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(
                        Environment.getExternalStorageDirectory()
                                + "/wltlib/zp.bmp");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    readSuccess = true;
                    showInfo();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("SetTextI18n")
    private void showInfo() {
        media = MediaPlayer.create(getActivity(), R.raw.read_card_success);
        media.start();
        if (nationBeanList.size() <= 0) {
            String json = AssetManagerUtils.getJson("nation.json", getActivity());
            nationBeanList = GsonUtils.fromJson(json, new TypeToken<List<NationBean>>() {
            }.getType());
        }
        for (NationBean nationBean : nationBeanList) {
            if (nationBean.getCode().equals(idCardDataBean.nation)) {
                minzuSpinner.setText(nationBean.getNation());
                break;
            }
        }
        refresh(isSequentialRead);
        idNoEt.setText(idCardDataBean.idCard);
        nameEt.setText(idCardDataBean.name);
//		minzuSpinner.setText("汉族");
        addressEt.setText(idCardDataBean.address);
        try {
            readSuccess = false;
            iv_photo.setImageBitmap(idCardDataBean.bIdbmp);
//			iv_photo.setImageURI(Uri.fromFile(new File(Environment.getExternalStorageDirectory()
//					+ "/wltlib/zp.bmp")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setIdInfo(String data) {
        Log.e("*****", "*************");
        flag_fromIdCard = true;
        String[] infos = data.split(",");
        System.out.println();
        nameEt.setText(infos[0]);
        minzuSpinner.setText(infos[2]);
        addressEt.setText(infos[4]);
        idNoEt.setText(infos[5]);
    }

    /**
     * 清空数据
     *
     * @author 王婷婷
     * @date 2017年6月5日 下午2:55:03
     */
    private void cleanData() {
        nameEt.setText("");
//        minzuSpinner.setText("汉族");
        addressEt.setText("");
        idNoEt.setText("");
        birthdayEt.setText("");
        sexRadio.clearCheck();
        exam_phone.setText("");
        check_isycf.setChecked(false);
        exam_login_zhuyuan_et.setText("");

        age = -1;
        sex = "";
    }

    /**
     * 点击登录事件
     *
     * @author 王婷婷
     * @date 2017年6月5日 下午2:56:59 民族
     */
    private void loginData() {
        String idNo = idNoEt.getText().toString().trim();
        String name = nameEt.getText().toString().trim();
        String birthday = birthdayEt.getText().toString().trim();
        String addr = addressEt.getText().toString().trim();
        String minzu = minzuSpinner.getText().toString().trim();
        String phone = exam_phone.getText().toString().trim();

        if (TextUtils.isEmpty(idNo) || TextUtils.isEmpty(name) || TextUtils.isEmpty(birthday) || TextUtils.isEmpty(addr)
                || TextUtils.isEmpty(minzu) || TextUtils.isEmpty(phone)) {
            ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("请将信息填写完整");
            return;
        }
        if (idNo.length() != 10) {
            if (!TextUtils.isEmpty(IDCardVerifyTool.Validate(idNo))) {
                ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("身份证号码错误，请修改再试");

                return;
            }
        }

        if (!GlobalConts.isPhoneNumberValid(phone)) {
            ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("请输入正确的手机号码");
            return;
        }
        if (NovaApplication.isBoolean_zhuyuan()) {
            if (TextUtils.isEmpty(exam_login_zhuyuan_et.getText())) {
                ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("请先获取住院号");
                return;
            } else {
                List<ARCHIVE_BASEINFO> zhuYuanList = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class,
                        "ZHUYUANHAO = '" + exam_login_zhuyuan_et.getText().toString() + "'");
                if (zhuYuanList.size() > 0) {
                    ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("住院号已存在");
                    return;
                }
            }
        }

        List<ARCHIVE_BASEINFO> idCardList = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class,
                "IDCARD = '" + idNo + "'");
        List<ARCHIVE_BASEINFO> idCardList1 = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class,
                "IDCARD = '" + idNo.toUpperCase() + "'");
        if (idCardList.size() == 0 && idCardList1.size() == 0) {

            userInfo = new ARCHIVE_BASEINFO();
            userInfo.setPHONE(phone);
            if (NovaApplication.isBoolean_zhuyuan()) {
                userInfo.setZHUYUANHAO(exam_login_zhuyuan_et.getText().toString());
            }

            userInfo.setADDR(addr);
            saveUserInfo(idNo.toUpperCase(), name, birthday, addr, minzu);
            userInfo.setCREATED_DATE(GlobalConts.dateFormat.format(new Date()));
            userInfo.setCREATER(SPUtil.getStr_jdrno(getContext()));
            userInfo.setCREATEORG(SPUtil.getStrjddwno(getContext()));
            userInfo.setCREATED_BY(SPUtil.getStr_jdrno(getContext()));
            Log.e("*******************", userInfo.getCREATED_BY() + "******" + userInfo.getCREATED_DATE());

            saveUserOrg();
            saveJBLX();

            String strWhere = "IDCARD LIKE '" + userInfo.getIDCARD() + "'";
            List<ARCHIVE_BASEINFO> infos = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class, strWhere);
            if (infos.size() > 0) {
                fDbManager.delete(infos.get(0));
            }
            NovaApplication.setUserInfo(userInfo);
            fDbManager.save(userInfo);
            getCJDAData(minzu);// 进行数据创建

            // 创建电子虚拟卡
            if (NovaApplication.isBoolean_dzjmjkk()) {
                if (scanSuccess) {
                    jumpNext();
                    scanSuccess = false;
                } else {
                    if (GlobalConts.isNetworkAvailable(getActivity())) {
                        if (TextUtils.isEmpty(GlobalConts.getUrlJMDZJKK())) {
                            noAddressDzjmjkk();

                        } else {
                            SimpleDateFormat dataBirth = new SimpleDateFormat("yyyyMMdd");
                            String dataBir = dataBirth.format(userInfo.getBIRTHDAY());
                            String data_arg1 = "<request><name>" + userInfo.getCUSTOMERNAME() + "</name><telephone>"
                                    + userInfo.getPHONE() + "</telephone><id_number>" + userInfo.getIDCARD()
                                    + "</id_number><id_type>01</id_type><id_card>" + userInfo.getIDCARD()
                                    + "</id_card><nation>" + userInfo.getNATION().replace("DM01-01_", "")
                                    + "</nation><sex>" + userInfo.getSEX().replace("DM01-08_", "") + "</sex><birthday>"
                                    + dataBir + "</birthday><address>" + userInfo.getHOUSEHOLD_ADDR()
                                    + "</address><auth_id_card>" + SPUtil.getstr_jdrIdcard(getActivity()) // 610125198907208102
                                    + "</auth_id_card><auth_name>" + SPUtil.getstr_jdr(getActivity())
                                    + "</auth_name></request>";//
                            getWebServiceJMJKKData(data_arg1, WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_ZC);

                        }
                    } else {
                        jumpNext();
                    }
                }
            } else {
                jumpNext();
            }
        } else {
            // 数据已存在
            ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("数据已存在，不需要建档");
            return;
        }
    }

    /**
     * 点击登录事件
     *
     * @author 王婷婷
     * @date 2017年6月5日 下午2:56:59 民族
     */
    private void loginData1() {
        String idNo = idNoEt.getText().toString().trim();
        String name = nameEt.getText().toString().trim();
        String birthday = birthdayEt.getText().toString().trim();
        String addr = addressEt.getText().toString().trim();
        String minzu = minzuSpinner.getText().toString().trim();
        String phone = exam_phone.getText().toString().trim();

        if (TextUtils.isEmpty(idNo) || TextUtils.isEmpty(name) || TextUtils.isEmpty(birthday) || TextUtils.isEmpty(addr)
                || TextUtils.isEmpty(minzu) || TextUtils.isEmpty(phone)) {
            ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("请将信息填写完整");
            return;
        }
        if (idNo.length() != 10) {
            if (!TextUtils.isEmpty(IDCardVerifyTool.Validate(idNo))) {
                ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("身份证号码错误，请修改再试");

                return;
            }
        }

        if (!GlobalConts.isPhoneNumberValid(phone)) {
            ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("请输入正确的手机号码");
            return;
        }
        if (NovaApplication.isBoolean_zhuyuan()) {
            if (TextUtils.isEmpty(exam_login_zhuyuan_et.getText())) {
                ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("请先获取住院号");
                return;
            } else {
                List<ARCHIVE_BASEINFO> zhuYuanList = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class,
                        "ZHUYUANHAO = '" + exam_login_zhuyuan_et.getText().toString() + "'");
                if (zhuYuanList.size() > 0) {
                    ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("住院号已存在");
                    return;
                }
            }
        }

        List<ARCHIVE_BASEINFO> idCardList = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class,
                "IDCARD = '" + idNo + "'");
        List<ARCHIVE_BASEINFO> idCardList1 = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class,
                "IDCARD = '" + idNo.toUpperCase() + "'");
        if (idCardList.size() == 0 && idCardList1.size() == 0) {

            userInfo = new ARCHIVE_BASEINFO();
            userInfo.setPHONE(phone);
            userInfo.setADDR(addr);
            if (NovaApplication.isBoolean_zhuyuan()) {
                userInfo.setZHUYUANHAO(exam_login_zhuyuan_et.getText().toString());
            }
            saveUserInfo(idNo.toUpperCase(), name, birthday, addr, minzu);
            userInfo.setCREATED_DATE(GlobalConts.dateFormat.format(new Date()));

            userInfo.setCREATER(SPUtil.getStr_jdrno(getContext()));
            userInfo.setCREATEORG(SPUtil.getStrjddwno(getContext()));
            userInfo.setCREATED_BY(SPUtil.getStr_jdrno(getContext()));

            saveUserOrg();
            saveJBLX();

            String strWhere = "IDCARD LIKE '" + userInfo.getIDCARD() + "'";
            List<ARCHIVE_BASEINFO> infos = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class, strWhere);
            if (infos.size() > 0) {
                fDbManager.delete(infos.get(0));
            }
            NovaApplication.setUserInfo(userInfo);
            fDbManager.save(userInfo);
            getCJDAData(minzu);// 进行数据创建

            // 创建电子虚拟卡
            if (NovaApplication.isBoolean_dzjmjkk()) {
                if (scanSuccess) {
                    jumpNext1();
                    scanSuccess = false;
                } else {
                    if (GlobalConts.isNetworkAvailable(getActivity())) {
                        if (TextUtils.isEmpty(GlobalConts.getUrlJMDZJKK())) {
                            noAddressDzjmjkk();

                        } else {
                            SimpleDateFormat dataBirth = new SimpleDateFormat("yyyyMMdd");
                            String dataBir = dataBirth.format(userInfo.getBIRTHDAY());
                            String data_arg1 = "<request><name>" + userInfo.getCUSTOMERNAME() + "</name><telephone>"
                                    + userInfo.getPHONE() + "</telephone><id_number>" + userInfo.getIDCARD()
                                    + "</id_number><id_type>01</id_type><id_card>" + userInfo.getIDCARD()
                                    + "</id_card><nation>" + userInfo.getNATION().replace("DM01-01_", "")
                                    + "</nation><sex>" + userInfo.getSEX().replace("DM01-08_", "") + "</sex><birthday>"
                                    + dataBir + "</birthday><address>" + userInfo.getHOUSEHOLD_ADDR()
                                    + "</address><auth_id_card>" + SPUtil.getstr_jdrIdcard(getActivity()) // 610125198907208102
                                    + "</auth_id_card><auth_name>" + SPUtil.getstr_jdr(getActivity())
                                    + "</auth_name></request>";//
                            getWebServiceJMJKKData(data_arg1, WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_ZC);

                        }
                    } else {
                        jumpNext1();
                    }
                }
            } else {
                jumpNext1();
            }

        } else {
            // 数据已存在
            ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("数据已存在，不需要建档");
            jumpNext1();
        }
    }

    private void loginData2() {
        String idNo = idNoEt.getText().toString().trim();
        String name = nameEt.getText().toString().trim();
        String birthday = birthdayEt.getText().toString().trim();
        String addr = addressEt.getText().toString().trim();
        String minzu = minzuSpinner.getText().toString().trim();
        String phone = exam_phone.getText().toString().trim();

        if (TextUtils.isEmpty(idNo) || TextUtils.isEmpty(name) || TextUtils.isEmpty(birthday) || TextUtils.isEmpty(addr)
                || TextUtils.isEmpty(minzu) || TextUtils.isEmpty(phone)) {
            ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("请将信息填写完整");
            return;
        }
        if (idNo.length() != 10) {
            if (!TextUtils.isEmpty(IDCardVerifyTool.Validate(idNo))) {
                ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("身份证号码错误，请修改再试");

                return;
            }
        }

        if (!GlobalConts.isPhoneNumberValid(phone)) {
            ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("请输入正确的手机号码");
            return;
        }
        if (NovaApplication.isBoolean_zhuyuan()) {
            if (TextUtils.isEmpty(exam_login_zhuyuan_et.getText())) {
                ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("请先获取住院号");
                return;
            } else {
                List<ARCHIVE_BASEINFO> zhuYuanList = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class,
                        "ZHUYUANHAO = '" + exam_login_zhuyuan_et.getText().toString() + "'");
                if (zhuYuanList.size() > 0) {
                    ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("住院号已存在");
                    return;
                }
            }
        }

        List<ARCHIVE_BASEINFO> idCardList = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class,
                "IDCARD = '" + idNo + "'");
        List<ARCHIVE_BASEINFO> idCardList1 = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class,
                "IDCARD = '" + idNo.toUpperCase() + "'");
        if (idCardList.size() == 0 && idCardList1.size() == 0) {

            userInfo = new ARCHIVE_BASEINFO();
            userInfo.setPHONE(phone);
            if (NovaApplication.isBoolean_zhuyuan()) {
                userInfo.setZHUYUANHAO(exam_login_zhuyuan_et.getText().toString());
            }

            userInfo.setADDR(addr);
            saveUserInfo(idNo.toUpperCase(), name, birthday, addr, minzu);
            userInfo.setCREATED_DATE(GlobalConts.dateFormat.format(new Date()));
            userInfo.setCREATER(SPUtil.getStr_jdrno(getContext()));
            userInfo.setCREATEORG(SPUtil.getStrjddwno(getContext()));
            userInfo.setCREATED_BY(SPUtil.getStr_jdrno(getContext()));
            Log.e("*******************", userInfo.getCREATED_BY() + "******" + userInfo.getCREATED_DATE());

            saveUserOrg();
            saveJBLX();

            String strWhere = "IDCARD LIKE '" + userInfo.getIDCARD() + "'";
            List<ARCHIVE_BASEINFO> infos = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class, strWhere);
            if (infos.size() > 0) {
                fDbManager.delete(infos.get(0));
            }
            NovaApplication.setUserInfo(userInfo);
            fDbManager.save(userInfo);
            getCJDAData(minzu);// 进行数据创建

            // 创建电子虚拟卡
            if (NovaApplication.isBoolean_dzjmjkk()) {
                if (scanSuccess) {
                    jumpNext2();
                    scanSuccess = false;
                } else {
                    if (GlobalConts.isNetworkAvailable(getActivity())) {
                        if (TextUtils.isEmpty(GlobalConts.getUrlJMDZJKK())) {
                            noAddressDzjmjkk();

                        } else {
                            SimpleDateFormat dataBirth = new SimpleDateFormat("yyyyMMdd");
                            String dataBir = dataBirth.format(userInfo.getBIRTHDAY());
                            String data_arg1 = "<request><name>" + userInfo.getCUSTOMERNAME() + "</name><telephone>"
                                    + userInfo.getPHONE() + "</telephone><id_number>" + userInfo.getIDCARD()
                                    + "</id_number><id_type>01</id_type><id_card>" + userInfo.getIDCARD()
                                    + "</id_card><nation>" + userInfo.getNATION().replace("DM01-01_", "")
                                    + "</nation><sex>" + userInfo.getSEX().replace("DM01-08_", "") + "</sex><birthday>"
                                    + dataBir + "</birthday><address>" + userInfo.getHOUSEHOLD_ADDR()
                                    + "</address><auth_id_card>" + SPUtil.getstr_jdrIdcard(getActivity()) // 610125198907208102
                                    + "</auth_id_card><auth_name>" + SPUtil.getstr_jdr(getActivity())
                                    + "</auth_name></request>";//
                            getWebServiceJMJKKData(data_arg1, WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_ZC);

                        }
                    } else {
                        jumpNext2();
                    }
                }
            } else {
                jumpNext2();
            }

        } else {
            // 数据已存在
            ((MainActivity_Menu_JTYS) getActivity()).showTextDialog("数据已存在，不需要建档");
            return;
        }
    }

    /**
     * 未检测到电子居民健康卡地址
     *
     * @author 王婷婷
     * @date 2017年12月26日 下午2:17:26
     */
    private void noAddressDzjmjkk() {
        new CommomDialog(getActivity(), R.style.dialog, "经检测，未找到电子居民健康卡接口地址，是否去设置？",
                new CommomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (confirm) {
                            Intent intent = new Intent(getActivity(), SystemSettingJMDZDAActivity.class);
                            getActivity().startActivity(intent);
                            dialog.dismiss();
                        } else {
                            Intent intent = new Intent(getActivity(), QYInfo.class);
                            getActivity().startActivity(intent);
                            dialog.dismiss();
                        }
                    }
                }).setTitle("温馨提示").setPositiveButton("去设置").setNegativeButton("取消").show();
    }

    /**
     * 获取服务条目data
     *
     * @author 王婷婷
     * @date 2017年5月31日 下午1:48:17
     */
    private void getCJDAData(final String nation) {
        final String sex = userInfo.getSEX().equals("DM01-08_1") ? "1" : "2";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        final String birthday = sdf.format(userInfo.getBIRTHDAY());
        final String str_jdrUserName = SPUtil.getStr_jdrno(getContext());
        saveFailUserData(str_jdrUserName, birthday, nation, sex);
    }

    /**
     * 保存失败的user数据
     */
    private void saveFailUserData(String str_jdrUserName, String birthday, String nation, String mysex) {
        String strWhere = "cardNum LIKE '" + userInfo.getIDCARD() + "'";
        List<JTYS_BASEINFO> infos = fDbManager.findAllByWhere(JTYS_BASEINFO.class, strWhere);
        if (infos.size() > 0) {
            fDbManager.delete(infos.get(0));
        }

        JTYS_BASEINFO info = new JTYS_BASEINFO();
        info.setID(GlobalContsJTYS.getUUID());
        info.setCardNum(userInfo.getIDCARD());
        info.setYsLoginNumber(str_jdrUserName);
        info.setName(userInfo.getCUSTOMERNAME());
        info.setSex(mysex);
        info.setBirthday(birthday);
        info.setAddress(userInfo.getHOUSEHOLD_ADDR());
        info.setOfficeId(NovaApplication.getJgbh());
        info.setNation(nation);
        info.setSign("0");
        info.setSource("0");
        info.setPopulationType(userInfo.getPOPULATION_TYPE());
        info.setTel(userInfo.getPHONE());
        String datetimeNow = GlobalContsJTYS.dateFormat.format(new Date());
        info.setUpdatedate(datetimeNow);
        info.setUpdater(NovaApplication.getJgrno());
        info.setCreatedate(datetimeNow);
        info.setCreater(NovaApplication.getJgrno());
        fDbManager.save(info);
    }

    /**
     * 显示文本信息
     */

    private NovaTextDialog textDialog;

    public void showTextDialog(String text) {
        if (this.textDialog == null) {
            this.textDialog = new NovaTextDialog(getContext());
        }
        this.textDialog.setText(text);
        this.textDialog.show();
    }

    private void jumpNext() {
        cleanData();
        NovaApplication.setUserInfo(userInfo);
        setSaveIDCard(userInfo.getIDCARD());
        Intent intent = new Intent(getActivity(), QYInfo.class);
        startActivity(intent);
    }

    private void jumpNext1() {
        cleanData();
        NovaApplication.setUserInfo(userInfo);
        setSaveIDCard(userInfo.getIDCARD());
//        Intent intent = new Intent(getActivity(), SBCLActivity.class);
        Intent intent = new Intent(getActivity(), BleMainActivity.class);
        startActivity(intent);
    }

    private void jumpNext2() {
        cleanData();
        NovaApplication.setUserInfo(userInfo);
        setSaveIDCard(userInfo.getIDCARD());
        Intent intent = new Intent(getActivity(), MainActivity_Menu_Tj.class);
        getActivity().startActivity(intent);
    }

    /**
     * 保存用户信息
     *
     * @author 王婷婷
     * @date 2017年3月2日 下午2:31:02
     */
    private void saveUserOrg() {
        userInfo.setCARDTYPE("0");
        String str_jdrno = SPUtil.getStr_jdrno(getContext());
        userInfo.setTOWNNAME(SPUtil.getstr_xz(getContext()));
        userInfo.setVILLAGENAME(SPUtil.getstr_cz(getContext()));
        userInfo.setCREATEUNIT_NAME(SPUtil.getstr_jddw(getContext()));
        userInfo.setCREATEMEN_NAME(SPUtil.getstr_jdr(getContext()));
        userInfo.setDOCTOR(str_jdrno);
        try {
            userInfo.setLAST_UPDATE_DATE(
                    GlobalConts.dateFormat.parse(GlobalConts.dateFormat.format(new Date())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        userInfo.setLAST_UPDATE_BY(str_jdrno);

        userInfo.setPROVINCE(SPUtil.getstr_p(getContext()));
        userInfo.setCITY(SPUtil.getstr_c(getContext()));
        userInfo.setCOUNTY(SPUtil.getstr_n(getContext()));
        userInfo.setSTREET(SPUtil.getstr_xzno(getContext()));

        userInfo.setCOMMITTEE(SPUtil.getstr_czno(getContext()));
    }

    /**
     * 保存idcard
     *
     * @param str_idCard
     * @author 王婷婷
     * @date 2017年6月9日 上午11:55:58
     */
    private void setSaveIDCard(String str_idCard) {
        SPUtil.setstr_idCard(getActivity(), str_idCard);
    }

    /**
     * 添加首次数据
     *
     * @author 王婷婷
     * @date 2017年6月21日 下午6:49:54
     */
    private void saveUserInfo(String idNo, String name, String birthday, String addr, String minzu) {

        userInfo.setSEX(("男").equals(sex) ? "DM01-08_1" : "DM01-08_2");
        userInfo.setIDCARD(idNo);
        userInfo.setCUSTOMERNAME(name);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date birthdayDate;
        try {
            birthdayDate = sdf.parse(birthday);
            userInfo.setBIRTHDAY(birthdayDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        List<BD_DD_INFO> minzuInfos = fDbManager.findAllByWhereInInfoDB(BD_DD_INFO.class,
                "DATAINFO = " + "'" + minzu + "'");
        userInfo.setNATION(minzuInfos.get(minzuInfos.size() - 1).getID());
        userInfo.setARCHIVEID(SPUtil.getstr_ssqno(getContext()));
        userInfo.setHOUSEHOLD_ADDR(addr);
        userInfo.setMINORITY(minzu);
        userInfo.setIS_UPDATE("Y");
    }

    /**
     * 设置孕妇选择框是否可见
     *
     * @param sex
     * @author 王婷婷
     * @date 2017年9月22日 上午10:13:18
     */
    private void setISycfVisible(String sex) {
        if ("女".equals(sex)) {
            check_isycf.setChecked(false);
            Log.e(TAG, "" + age);
            if (age >= 14 && age <= 55) {
                linear_sfycf.setVisibility(View.VISIBLE);
            } else {
                linear_sfycf.setVisibility(View.GONE);
            }
        } else {
            linear_sfycf.setVisibility(View.GONE);
            check_isycf.setChecked(false);
        }
    }

    /**
     * 保存人群疾病类型
     *
     * @author 王婷婷
     * @date 2017年9月22日 上午10:15:30
     */
    private void saveJBLX() {
        HD_PERSONAL_JKTZ jktz = new HD_PERSONAL_JKTZ();
        if (age >= 14 && age <= 55 && check_isycf.isChecked()) {
            // 孕妇
            jktz.setIsycf(ISTAG);
        } else if (age >= 65) {
            // 老年人
            jktz.setIslnr(ISTAG);
        } else if (age <= 6) {
            // 儿童
            jktz.setIset(ISTAG);
        }
        jktz.setIdCard(userInfo.getIDCARD());
        fDbManager.save(jktz);
        getPop();
    }

    /**
     * 用户表中 --人群分类（用作 家庭签约医生）
     *
     * @author 王婷婷
     * @date 2017年3月2日 下午2:42:35
     */
    private void getPop() {
        String population = "";
        if (age >= 14 && age <= 55 && check_isycf.isChecked()) {
            population = PeopleType.WOMAN;
        } else if ((age) >= 65) {
            population = PeopleType.OLD;
        } else if (age <= 6) {
            population = PeopleType.CHILD;
        } else {
            population = PeopleType.YBRQ;
        }
        if (!TextUtils.isEmpty(userInfo.getPOPULATION_TYPE())) {
            if (population.equals(PeopleType.YBRQ)) {
                // 一般人群
                return;
            }
            String pop = userInfo.getPOPULATION_TYPE();
            String[] pops = pop.split(",");
            if (!Arrays.asList(pops).contains(population)) {
                pop = pop + "," + population;
                userInfo.setPOPULATION_TYPE(pop);
            }
        } else {
            userInfo.setPOPULATION_TYPE(population);
        }
    }

    /**
     * 注册电子居民健康卡---------------------start--------------------------------------
     */

    private void initProgressDialog() {
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setTitle("正在同步数据");
        mProgressDialog.setMessage("请稍候...");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == 2046) {
                String str_result = data.getStringExtra("resultString");
                if (TextUtils.isEmpty(str_result)) {
                    return;
                }
                Log.e(TAG, "onActivityResult():" + str_result);
                if (NovaApplication.isBoolean_dzjmjkk()) {
                    if (TextUtils.isEmpty(GlobalConts.getUrlJMDZJKK())) {
                        noAddressDzjmjkk();

                    } else {
                        // 扫描结果进行处理
                        String data_arg1 = "<qr_code>" + str_result + "</qr_code>";
                        String strCurrTime = GlobalConts.datetimeFormat.format(new Date());
                        String imei = SPUtil.getRegisterImei(getActivity());

                        String use_citycode = "";
                        String use_cityname = "";
                        //五级机构(五级机构空--获取四级机构)
                        if ("".equals(SPUtil.getstr_czno(getActivity()))) {
                            use_citycode = SPUtil.getstr_xzno(getActivity());
                            use_cityname = SPUtil.getstr_xz(getActivity());
                        } else {
                            use_citycode = SPUtil.getstr_czno(getActivity());
                            use_cityname = SPUtil.getstr_cz(getActivity());
                        }
                        String hospital_code = SPUtil.getStrjddwno(getActivity());
                        String hospital_name = SPUtil.getstr_jddw(getActivity());

                        String dataOne = "<time>" + strCurrTime + "</time><sam>" + imei + "</sam><use_citycode>" + use_citycode + "</use_citycode><use_cityname>" + use_cityname + "</use_cityname><hospital_code>" + hospital_code + "</hospital_code><hospital_name>" + hospital_name + "</hospital_name>";
                        String dataOther = "<channel_code>99</channel_code><channel_name>其他</channel_name><medstep_code>000000</medstep_code><medstep_name>其他</medstep_name>";
                        String dataArg = "<request>" + data_arg1 + dataOne + dataOther + "</request>";
                        Log.e(TAG, dataArg);
                        getWebServiceJMJKKData(dataArg, WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_GETDATA_FROMCODEIMG);
                    }
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }

    /**
     * 获取权限
     */
    public void getQuanXian() {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA},
                    CAMERA_REQUEST_CODE);
        } else {
            Intent intent = new Intent(getActivity(), CaptureActivity.class);
            startActivityForResult(intent, 2046);
        }
    }

    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                startActivityForResult(intent, 2046);
            } else {
                GlobalConts.showToast(getActivity(), "操作摄像头权限，已被禁止");
            }
        }
    }

    /**
     * 居民电子健康卡 注册、扫描、获取二维码
     *
     * @param data_arg1
     * @param type
     * @author 王婷婷
     * @date 2017年12月18日 下午5:51:17
     */
    private void getWebServiceJMJKKData(final String data_arg1, final String type) {
        if (TextUtils.isEmpty(type)) {
            return;
        }
        String dataCurrentTime = GlobalConts.datetimeFormat.format(new Date());

        /**
         * bussinessCode 电子居民健康卡注册 RHC_E0001 电子居民健康卡二维码 RHC_E0002 电子居民健康卡的二维码验证
         * RHC_E0003 电子居民健康卡注销 RHC_E0004 电子居民健康卡二维码获取 RHC_E0005 电子居民健康卡注册（现场认证）
         * RHC_E0006
         *
         */
        String progressDialogtitleMsg = "";
        String bussinessCode = "";
        if (WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_ZC.equals(type)) {
            bussinessCode = "RHC_E0006";
            progressDialogtitleMsg = "正在注册电子居民健康卡信息...";
        } else if (WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_GETCODEIMAGE_FROMIDCARD.equals(type)) {
            bussinessCode = "RHC_E0002";
            // progressDialogtitleMsg="正在获取电子居民健康卡信息...";
        } else if (WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_GETDATA_FROMCODEIMG.equals(type)) {
            bussinessCode = "RHC_E0003";
            progressDialogtitleMsg = "正在获取电子居民健康卡信息...";
        }

        final String data_arg0 = "<request><msgGuid>" + GlobalConts.getUUID()
                + "</msgGuid><msgType>1</msgType><bussinessCode>" + bussinessCode + "</bussinessCode><msgCreateTime>"
                + dataCurrentTime + "</msgCreateTime><orgId></orgId><appCode>"
                + WebServiceConts.WEBSERVICE_DZJMJKK_APPCODE + "</appCode><userName>"
                + WebServiceConts.WEBSERVICE_DZJMJKK_USERNAME + "</userName><userPwd>"
                + WebServiceConts.WEBSERVICE_DZJMJKK_USERPWD + "</userPwd><stdVerCode>1.1</stdVerCode></request>";// ]]>
        initProgressDialog();
        ((MainActivity_Menu_JTYS) getActivity()).showProgressDialog(progressDialogtitleMsg);
        Handler handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                try {
                    new JmdzjkkWebService(getActivity()) {

                        @Override
                        public void start(String message) {
                            super.start(message);
                            System.out.println("test111" + message);

                        }

                        @Override
                        public void onSynchronize(String message, int syncCount, int dataSize) {
                            super.onSynchronize(message, syncCount, dataSize);
                        }

                        @Override
                        public void complete(final String message) {
                            super.complete(message);
                            Log.e(TAG, message);
                            ((MainActivity_Menu_JTYS) getActivity()).cancelProgressDialog();
                            if (mProgressDialog != null) {
                                mProgressDialog.dismiss();
                                mProgressDialog.cancel();
                            }
                            ((MainActivity_Menu_JTYS) getActivity()).runOnUiThread(new Runnable() {

                                @Override
                                public void run() {

                                    if (WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_ZC.equals(type)) {
                                        // 注册
                                        getZcDataResult(message);
                                    } else if (WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_GETCODEIMAGE_FROMIDCARD
                                            .equals(type)) {
                                        // 申请二维码信息
                                        getZcQcodeImageDataResult(message);
                                    } else if (WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_GETDATA_FROMCODEIMG
                                            .equals(type)) {
                                        // 通过二维码读取用户信息
                                        getDataQcodeResult(message);
                                    }

                                }

                            });
                        }

                        @Override
                        public void onError(String message) {
                            ((MainActivity_Menu_JTYS) getActivity()).cancelProgressDialog();
                            if (mProgressDialog != null) {
                                mProgressDialog.dismiss();
                                mProgressDialog.cancel();
                            }
                            ((MainActivity_Menu_JTYS) getActivity()).runOnUiThread(new Runnable() {

                                @Override
                                public void run() {

                                }
                            });
                        }

                        ;
                    }.synchrodata(data_arg0, data_arg1);// ,WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_GETCODEDATA
                } catch (Exception e) {
                    e.printStackTrace();
                    if (mProgressDialog != null) {
                        mProgressDialog.dismiss();
                        mProgressDialog.cancel();
                    }
                    ((MainActivity_Menu_JTYS) getActivity()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                        }
                    });
                }

            }
        };
        handler.sendMessage(new Message());
    }

    /**
     * 获取 二维码成功之后的数据处理
     *
     * @param message
     * @author 王婷婷
     * @date 2017年12月18日 下午6:02:46
     */
    private void getDataQcodeResult(final String message) {
        DZJMJKKXQcodeBean ecg = DzjmjkkDataTool.getDataCodeFromXML(message);
        if (ecg != null) {
            if ("success".equals(ecg.getResult())) {
                scanSuccess = true;
                idNoEt.setText(ecg.getId_card());
                nameEt.setText(ecg.getName());
                String birth = ecg.getBirthday();
                if (!TextUtils.isEmpty(birth)) {
                    if (birth.length() == 8) {
                        birth = birth.substring(0, 4) + "-" + birth.substring(4, 6) + "-" + birth.substring(6, 8);
                        birthdayEt.setText(birth);
                    }
                } else {
                    birthdayEt.setText("");
                }
                String strSex = ecg.getSex();
                // 性别：0 未知的性别 1 男性 2 女性 9 未说明的性别
                if (!TextUtils.isEmpty(strSex)) {
                    if ("1".equals(sex)) {
                        mailRadio.setChecked(true);
                    } else if ("2".equals(sex)) {
                        famailRadio.setChecked(true);
                    }
                } else {
                    sexRadio.clearCheck();
                }

                String str_nationId = ecg.getNation();
                if (!TextUtils.isEmpty(str_nationId)) {
                    List<BD_DD_INFO> minzuList = fDbManager.findAllByWhereInInfoDB(BD_DD_INFO.class,
                            "ID = 'DM01-01_" + str_nationId + "'");
                    minzuSpinner.setText(minzuList.get(0).getDATAINFO());
                }
                addressEt.setText(ecg.getAddress());
                exam_phone.setText(ecg.getTelephone());
            } else {
                scanSuccess = false;
                Toast.makeText(getContext(), ecg.getDesc(), Toast.LENGTH_LONG).show();
            }
        } else {
            scanSuccess = false;
            Toast.makeText(getContext(), "未获取到档案数据 ", Toast.LENGTH_LONG).show();
        }
    }

    DZJMJKKXcrzBean dZJMJKKXcrzBean = null;

    /**
     * 获取注册成功之后的数据
     *
     * @param message
     * @author 王婷婷
     * @date 2017年12月18日 下午6:04:54
     */
    private void getZcDataResult(final String message) {
        dZJMJKKXcrzBean = DzjmjkkDataTool.getZCDataFromXML(message);
        if (dZJMJKKXcrzBean != null) {
            if ("success".equals(dZJMJKKXcrzBean.getResult())) {
                //注册成功之后，获取用户二维码
                String data_arg1 = "<request><id_card>" + userInfo.getIDCARD()
                        + "</id_card><id_type></id_type><id_number></id_number><qrcode_type>1</qrcode_type></request>";
                getWebServiceJMJKKData(data_arg1, WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_GETCODEIMAGE_FROMIDCARD);
            } else {
                if (dZJMJKKXcrzBean.getDesc() != null) {
                    Toast.makeText(getActivity(), dZJMJKKXcrzBean.getDesc(), Toast.LENGTH_LONG).show();
                }
                jumpNext();
            }
        } else {
            jumpNext();
        }
    }

    /**
     * 获取注册成功之后的数据
     *
     * @param message
     * @author 王婷婷
     * @date 2017年12月18日 下午6:04:54
     */
    private void getZcQcodeImageDataResult(final String message) {
        DZJMJKKSQCodeImageBean ecg = DzjmjkkDataTool.getZCImageDataFromXML(message);
        if (ecg != null) {
            if ("success".equals(ecg.getResult())) {
                String ecgImageData = ecg.getQr_code_imgtext();
                if (!TextUtils.isEmpty(ecgImageData)) {
                    zcImageCodeSuccessData(ecgImageData);

                } else {
                    zcSuccessData();
                }

            } else {
                zcSuccessData();
            }
        } else {
            zcSuccessData();
        }
    }

    /**
     * 注册成功data
     *
     * @author 王婷婷
     * @date 2017年12月19日 上午9:32:21
     */
    private void zcSuccessData() {
        String str_status = DzjmjkkDataTool.zcSuccessPubData(dZJMJKKXcrzBean);
        Toast.makeText(getContext(), "注册电子居民健康卡成功，审核状态为: " + str_status, Toast.LENGTH_LONG).show();
        new CommomDialog(getActivity(), R.style.dialog, "", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    jumpNext();
                    dialog.dismiss();
                }
            }
        }).setTitle("关注电子居民健康卡二维码").setImageContent(R.drawable.qrcode_for_dzjmjkk).setImage2Content("")
                .setPositiveButton("下一步").setNegativeButtonVisibility(View.GONE).show();
    }

    /**
     * 注册成功data 申请二维码
     *
     * @author 王婷婷
     * @date 2017年12月19日 上午9:32:21
     */
    private void zcImageCodeSuccessData(String imgBase64String) {
        String str_status = DzjmjkkDataTool.zcSuccessPubData(dZJMJKKXcrzBean);
        Toast.makeText(getContext(), "注册电子居民健康卡成功，审核状态为: " + str_status, Toast.LENGTH_LONG).show();
        new CommomDialog(getActivity(), R.style.dialog, "", new CommomDialog.OnCloseListener() {

            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    jumpNext();
                    dialog.dismiss();
                }
            }
        }).setTitle("关注电子居民健康卡二维码").setImageContent(R.drawable.qrcode_for_dzjmjkk).setImage2Content(imgBase64String)
                .setPositiveButton("下一步").setNegativeButtonVisibility(View.GONE).show();
    }

    @Override
    public void onStart() {
        super.onStart();
        isSequentialRead = false;
    }

    @Override
    public void onResume() {
        super.onResume();
//        minzuSpinner.setText("汉族");
        isFont = true;
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e("隐藏页面", "onResume");
        if (DeviceUtil.compareDeviceName()) {
            soundPool.release();
            isSequentialRead = false;
        }
        isFont = false;
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (activeService != null) {
            activeService.shutdown();
        }
        readSuccess = false;
        if (media != null) {
            media.stop();
            media.release();
            media = null;
        }

        // 新设备读卡器
        if (cardSDK != null) {
            cardSDK.unRegisterCard();
        }

    }

    @Override
    public void onDestroy() {
        if (DeviceUtil.compareDeviceName()) {
            isSequentialRead = false;
            mediaPlayer.release();
            mediaPlayer = null;
        }
        getActivity().unregisterReceiver(myBroadcastReceiver);
        super.onDestroy();
    }

}
